package com.redisson.controller;

import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
public class StockController {
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	@Resource
	private Redisson redisson;
	@GetMapping("/stock")
	public String stock(){
		/*String lockValue = UUID.randomUUID().toString();
		Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", lockValue, 3, TimeUnit.SECONDS);*/
		RLock lock = redisson.getLock("lock");
		lock.lock(3,TimeUnit.SECONDS);
//		if (lock) {
			int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));

			try {
				if (stock>0){
					stock=stock-1;
					stringRedisTemplate.opsForValue().set("stock",stock+"");
					System.out.println("库存还剩"+stock);
					return "success";
				}else{
					System.out.println("库存不足");
					return "fail";
				}
			}finally {
				lock.unlock();
				/*if (lockValue.equals(stringRedisTemplate.opsForValue().get("lock"))) {
					stringRedisTemplate.delete("lock");
				}*/
			}
//		}else {
//			System.out.println("获取锁失败");
//			return "error";
//		}
	}
	@GetMapping("/top")
	public String top(){
		stringRedisTemplate.opsForZSet().incrementScore("book","完美世界",100);
		stringRedisTemplate.opsForZSet().incrementScore("book","大主宰",98);
		stringRedisTemplate.opsForZSet().incrementScore("book","遮天",88);
		stringRedisTemplate.opsForZSet().incrementScore("book","大奉打更人",85);
		stringRedisTemplate.opsForZSet().incrementScore("book","炎帝传说",70);
		stringRedisTemplate.opsForZSet().incrementScore("book","疾风传",99);
		stringRedisTemplate.opsForZSet().incrementScore("book","博人传",46);
		stringRedisTemplate.opsForZSet().incrementScore("book","凤逆天下",33);
		stringRedisTemplate.opsForZSet().incrementScore("book","一念永恒",84);
		stringRedisTemplate.opsForZSet().incrementScore("book","一念神魔",66);
		System.out.println("--------倒序--------");
		Set<ZSetOperations.TypedTuple<String>> book = stringRedisTemplate.opsForZSet().reverseRangeWithScores("book", 0, 2);
		if (book != null) {
			book.forEach(b->System.out.println(b.getValue()+":"+b.getScore()));
		}
		System.out.println("--------正序--------");
		Set<ZSetOperations.TypedTuple<String>> book1 = stringRedisTemplate.opsForZSet().rangeWithScores("book", 0, 4);
		if (book1 != null) {
			book1.forEach(b->System.out.println(b.getValue()+":"+b.getScore()));
		}
		return "success";
	}
}